package com.pe.pgn.clubpgn.webapp.controller.articulo;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import com.pe.pgn.clubpgn.common.CLPConstantes;
import com.pe.pgn.clubpgn.domain.ClpbCategoria;
import com.pe.pgn.clubpgn.domain.ClpdArticulo;
import com.pe.pgn.clubpgn.domain.ClpdUnidadMedida;
import com.pe.pgn.clubpgn.domain.beans.BNArticulo;
import com.pe.pgn.clubpgn.service.ArticuloService;
import com.pe.pgn.clubpgn.service.CategoriaService;
import com.pe.pgn.clubpgn.service.UnidadMedidaService;
import com.pe.pgn.clubpgn.webapp.controller.BaseFormController;

@Controller
@RequestMapping("/articulo/**")
public class ArticuloController extends BaseFormController {

	@Autowired
	private ArticuloService articuloService;
	
	@Autowired
	private CategoriaService categoriaService;
	
	@Autowired
	private UnidadMedidaService unidadMedidaService;
	
	private static final String ES_EDITABLE = "esEditable";
	
	@RequestMapping(value = "/articulolist.html")
    public void listarArticulos(Model model) {
		
		List<ClpdArticulo> articulos = articuloService.obtenerArticulos();
		List<ClpbCategoria> categorias = categoriaService.obtenerTodoCategorias();	
		
		model.addAttribute("articulos", articulos);
		model.addAttribute("categorias", categorias);
	}
	
	@RequestMapping(value = "/articuloform.html", method = RequestMethod.GET)
	public @ModelAttribute("articulo") ClpdArticulo verArticulo(
				@RequestParam(value = "id", required = false) Long id, Model model) {
		
		ClpdArticulo articulo = new ClpdArticulo();
		BNArticulo comparar=null;
		if (id != null) {
			
			articulo = articuloService.obtenerArticulo(id);//le llega  el id
			 comparar=articuloService.obtenerArticuloPorID(id);
			boolean articuloConDependencias = articuloService.esArticuloConDependencias(id);			
			if(articuloConDependencias){
				model.addAttribute(ES_EDITABLE, Boolean.FALSE);	
				
			}
			else{				
				model = asignarVariablesComunes(articulo, Boolean.TRUE, model);
				if(comparar.getStNoManejaStock().equals('Y')){
					articulo.setStNoManejaStock(Boolean.TRUE);
				}else if(comparar.getStManejaStockPuntoCanje().equals('Y')){
					articulo.setStManejaStockPuntoCanje(Boolean.TRUE);
				}else if(comparar.getStManejaStockAlmPrincipal().equals('Y')){
					articulo.setStManejaStockAlmPrincipal(Boolean.TRUE);
				}else if(comparar.getStInstantaneoNormal().equals('Y')){
					articulo.setStInstantaneoNormal(Boolean.TRUE);
				}else if(comparar.getStInstantaneoVale().equals('Y')){
					articulo.setStInstantaneoVale(Boolean.TRUE);
				}
			}					
			return articulo;
		}
		
		model = asignarVariablesComunes(articulo, Boolean.TRUE, model);	
		
		articulo.setStArticulo(Boolean.TRUE);

		
		articulo.setVaPrecioReferencial(BigDecimal.ZERO);
		articulo.setVaStockActual(BigDecimal.ZERO);
		articulo.setVaStockDisponible(BigDecimal.ZERO);
		articulo.setStManejaStockPuntoCanje(Boolean.TRUE);
		
		return articulo;
	}
	
	@RequestMapping(value = "/articuloform.html", method = RequestMethod.POST)
	public String guardarArticulo(@ModelAttribute("articulo") ClpdArticulo articulo,
			BindingResult result, SessionStatus status, HttpServletRequest request, Model model) {

				if(articulo.isStInstantaneoVale()==true && articulo.getCantidad()==null ){
						saveError(request, getText("articuloform.error.elegir.tipo.articulo.cantidad", request.getLocale()));
						model.addAttribute("articulo", articulo);
						return "/articulo/articuloform";

					
				}
			
		try{
			
			if (result.hasErrors()) {				
				model = asignarVariablesComunes(articulo, Boolean.TRUE, model);
				model.addAttribute("articulo", articulo);
				
				return "/articulo/articuloform";			
			}
			
			articuloService.guardarArticulo(articulo);
			saveMessage(request, getText("articuloform.added", articulo.getDeArticulo().length() > CLPConstantes.LIMITE_CADENA ?
					articulo.getDeArticulo().substring(0, CLPConstantes.LIMITE_CADENA)
					.concat(CLPConstantes.PUNTOS_SUSPENSIVOS) : articulo.getDeArticulo(), 
					request.getLocale()));
			model.addAttribute("articulo", articulo);
			return "redirect:articuloform.html?from=list&id="+articulo.getId();
			
		}catch (Exception e) {
			
			saveError(request, getText("errors.general", request.getLocale()));				
			boolean articuloConDependencias = articuloService.esArticuloConDependencias(articulo.getId());			
			if(articuloConDependencias){
				model.addAttribute(ES_EDITABLE, Boolean.FALSE);	
			}
			else{				
				model = asignarVariablesComunes(articulo, Boolean.TRUE, model);
			}					
			
			model.addAttribute("articulo", articulo);
			return "/articulo/articuloform";
		}		
	}
	
	@RequestMapping(value = "/eliminararticulo.html")
	public String eliminarArticulo(@RequestParam(value = "id", required = false) Long id, 
			HttpServletRequest request, Model model) {
		
		try {					
			
			articuloService.eliminarArticulo(id);
			saveMessage(request, getText("articuloform.deleted", request.getLocale()));
			return "redirect:articulolist.html";
			
		} catch (Exception e) {
			
			saveError(request, getText("errors.general", request.getLocale()));
			ClpdArticulo articulo = articuloService.obtenerArticulo(id);
			model = asignarVariablesComunes(articulo, Boolean.TRUE, model);
			model.addAttribute("articulo", articulo);
			return "/articulo/articuloform";	
		}
	}
	
	public Model asignarVariablesComunes(ClpdArticulo articulo, boolean esEditable, Model model){
		
		List<ClpbCategoria> categorias = categoriaService.obtenerTodoCategorias();	
		model.addAttribute("categorias", categorias);
		
		if(articulo.getId() == null && !categorias.isEmpty()){
			ClpbCategoria categoria = categorias.get(categorias.size() - 1);
			articulo.setCoCodigoArticulo(categoria.getCoCodigoCategoria());
		}
		
		List<ClpdUnidadMedida> unidadesMedida = unidadMedidaService.obtenerUnidadesMedida();
		model.addAttribute("unidadesMedida", unidadesMedida);
		
		model.addAttribute(ES_EDITABLE, esEditable);
		
		return model;
	}	
	
	public String asignarVariablesExcepcion(ClpdArticulo articulo, Model model){
		
		if(articulo.getId() != null){
			model.addAttribute("articulo", articulo);
			return "redirect:articuloform.html?from=list&id="+articulo.getId();
		}
		else{					
			model = asignarVariablesComunes(articulo, Boolean.TRUE, model);
			model.addAttribute("articulo", articulo);
			return "/articulo/articuloform";
		}
	}
}
